-- test.lua

local array = dofile("test.dat")

-- print contents
for i,v in pairs(array) do
    print(i,v)
end

-- string
local s1,s2 = "Hello","World"
print(s1..' '..s2)

-- compare
local a = {1,2}
b = a
print(a==b, a~=b)
b = {1,2}
print(a==b, a~=b)

-- logical
print(4 and 5)
print(4 or 5)
print(nil and 13)
print(false and 13)
print(false or 5)
print(not 4 and 5)

-- table
myData = {name="kid"}
myData[0] = "foo"
myData[1] = 42
myData["bar"] = "baz"
table.foreach(myData, print)

T1 = {}
T1["John"] = {Age=27, Gender="Male"}
print(T1.John.Age, T1.John.Gender)

T1 = 
{
    10, -- [1] = 10
    [100] = 40,
    John = -- ["John"] = 
    {
        Age = 27, -- ["Age"] = 27
        Gender = "Male" -- ["Gender"] = "Male"
    },
    20 -- [2] = 20
}
print("Attention:" .. T1[100])
table.foreach(T1, print)

-- Function
sum = 
function (a, b, ...)
    sum = a+b
    for _,v in ipairs(arg) do
        sum = sum + v
    end
    print(sum)
    return 1,2,3
end

print(sum(1,2,3))

function pythagorean(a,b)
    local c2 = a^2 + b^2
    return math.sqrt(c2)
end
print(pythagorean(3,4))

-- Object
t = 
{
    Age = 27,
    add = function(self, n)
            self.Age = self.Age + n
          end
}
t["add"](t, 10) -- t:add(10) -- t.add(t, 10)
print(t.Age)

-- metatable
mt = {}

function String(string)
    return setmetatable({value = string or ''}, mt)
end

-- a is String table, b is string
function mt.__add(a, b)
    return String(a.value..b)
end

s = String('Hello')
print((s + ' There' + ' World').value)

print(mt == getmetatable(s))

function Memoize(func, t)
    return setmetatable(t or {},
        {__index = 
         function(t, k)
            local v = func(k)
            t[k] = v
            return v
         end
        })
end

COLORS = {"red", "blue", "green", "yellow", "black"}
color = Memoize(function(node)
                    return COLORS[math.random(1, table.getn(COLORS))]
                end)
print(color[1], color[2], color[1])

-- scope lexical
x = 10
do
    local x = x
    print(x) --10
    x = x + 1
    do 
        local x = x + 1
        print(x) --12
    end
    print(x) --11
end
print(x) --10

RO = {ok=0, err=-1}
setmetatable(_G, {__index=RO})
print(err)

math.randomseed(os.time())
local r = math.random(5)
print("r is " .. r)
local rr
if r > 3 then
    rr = 1
else
    rr = 0
end
print(rr)


